<template>
  <div>
    <el-row>
      <!-- 饼图 -->
      <div class="task1-chart" ref="task1"></div>
    </el-row>
    <el-row>
      <!-- 一些文字数据？ -->
      <div
        style="
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          font-family: 'Microsoft YaHei', sans-serif;
        "
      >
        <el-row>
          <span>维保任务</span>
        </el-row>
        <el-row>
          <span>总数: {{ originalData[0] }}</span>
        </el-row>
        <el-row>
          <span>已完成: {{ originalData[1] }}</span>
        </el-row>
      </div>
    </el-row>
  </div>
</template>
<!-- 元素的class名字不能一样，最后将vue文件集中在一个页面中，造成class名字重复，无法使用样式 -->
<script>
import * as echarts from "echarts";
import { getMaintenanceCount } from "@/api/business/maintenance";
export default {
  name: "task1",

  mounted() {
    this.getTaskCount();
  },
  beforeUnmount() {
    if (this.task1) {
      this.task1.dispose();
    }
    window.removeEventListener("resize", this.resizeHandler);
  },
  data() {
    return {
      task1: null,
      resizeHandler: null, // 初始化 resizeHandler
      tableData: [],
      originalData: [],
    };
  },
  watch: {
    tableData: {
      handler(newData) {
        // 当 showdata 发生变化时，更新图表数据
        // 确保 DOM 完全加载后再初始化 ECharts
        this.delayInitChart();
        // console.log("Updated showdata3:", newData); // 打印更新后的数据
        // console.log("tablrData3:", this.tableData);
        if (this.task1) {
          this.task1.setOption({
            series: [
              {
                data: newData, // 更新数据
              },
            ],
          });
        }
      },
      deep: true, // 深度监听
    },
  },
  methods: {
    //  获取维保任务总数和已完成维保任务的数量
    getTaskCount() {
      getMaintenanceCount().then((response) => {
        this.originalData = response.data;
        // console.log("originalData:", this.originalData);
        this.rebuildData2();
      });
    },
    delayInitChart() {
      // 延迟初始化 ECharts
      this.ensureDomReady().then(() => {
        this.initChart3();
      });
    },
    ensureDomReady() {
      return new Promise((resolve) => {
        const checkDom = () => {
          const chartElement = this.$refs.task1;
          if (
            chartElement &&
            chartElement.clientWidth > 0 &&
            chartElement.clientHeight > 0
          ) {
            resolve();
          } else {
            setTimeout(checkDom, 50); // 每 50ms 检查一次
          }
        };
        checkDom();
      });
    },
    initChart3() {
      this.task1 = echarts.init(this.$refs.task1);
      const chartElement = this.$refs.task1;

      if (
        !chartElement ||
        chartElement.clientWidth <= 0 ||
        chartElement.clientHeight <= 0
      ) {
        console.error("Chart element is not ready");
        return;
      }
      this.task1.setOption({
        title: {
          text: "维保任务统计",
          left: "center",
          top: "-2%",
        },

        // 'item'
        // 数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。
        // 当鼠标移动在图上时，会显示数据
        tooltip: {
          trigger: "item",
        },
        // legend: {
        //   top: "5%",
        //   left: "center",
        // },
        color: [
          "#ef6567", //橙红
          "#f9c956", // 金黄
          "#75bedc",
          "#5470c6",
          "#91cd77",
        ],
        series: [
          {
            name: "维保任务",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            padAngle: 5,
            itemStyle: {
              borderRadius: 10,
            },
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 15,
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: this.tableData,
          },
        ],
      });
      const resizeHandler = this.debounce(() => {
        this.task1.resize();
      }, 300);

      window.addEventListener("resize", resizeHandler);

      // 保存 resizeHandler 以便在 beforeUnmount 中移除
      this.resizeHandler = resizeHandler;
    },
    debounce(fn, delay = 1000) {
      let timer = null;
      return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, args);
        }, delay);
      };
    },

    // 重组获取的数据
    rebuildData2() {
      // console.log("数据：", this.showdata);
      //   维保任务总数量
      let tasknum = this.originalData[0];
      console.log("tasknum", tasknum);
      //  已完成维保任务数量
      let tasknum_finish = this.originalData[1];
      //  未完成维保任务数量
      let tasknum_unfinish = tasknum - tasknum_finish;

      let tasknum_finish_data = {
        value: tasknum_finish,
        name: "已完成维保任务数量",
      };
      let tasknum_unfinish_data = {
        value: tasknum_unfinish,
        name: "未完成维保任务数量",
      };

      this.tableData.push(tasknum_finish_data);
      this.tableData.push(tasknum_unfinish_data);

      //   console.log("tableData:", this.tableData);
    },
  },
};
</script>

<style lang="scss" scoped>
.task1-chart {
  height: 150px;
  width: 100%;
}
</style>
